# coding=utf-8
#-------------------------------------------------------------------------------
# Name:        模块1
# Purpose:
#
# Author:      mu
#
# Created:     07/12/2020
# Copyright:   (c) mu 2020
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import time
import os
from pynput.mouse import Listener
from pynput.keyboard import Key, Listener as KBListener
import pyautogui
import pywinauto
import util

app = util.get_Application()

path = util.Conf.get_make_path()
time_format = util.Conf.time_format

of=None

def cap_win_pic(x, y, event, extra=''):
    win = app.top_window()
##    print((l,t,w,h), x, y)
    region = util.get_region(win, x, y)
    if region:
        name = time.strftime(time_format)
        point = util.ScreenToClient(win.handle, x, y)[0]
        of.write('%s %s (%d,%d) %s\n'%(name, event, point.x, point.y, extra))
##        im_full = pyautogui.screenshot()
        im_win = win.capture_as_image()
        im_point = pyautogui.screenshot(region=region)

##        im_full.save(os.path.join(path, '%s-%s.png'%(name, 'full')))
        im_win.save(os.path.join(path, '%s-%s.png'%(name, event)))
        im_point.save(os.path.join(path, '%s-%s-point.png'%(name, event)))

def on_click(x,y, button, pressed):
    if pressed:
        cap_win_pic(x,y, 'click')

def on_scroll(x, y, dx, dy):
    cap_win_pic(x,y, 'scroll', (dx, dy))

def on_press(key):
    pass
##    print('{0} pressed'.format(key))

def on_release(key):
##    print('{0} release'.format(key))
    if key == Key.esc:
        return False

hook = 0
def event_handler(event):
    k = ''
    for s in dir(event):
        if s.startswith('_'):
            continue
        k += '%s:%s,'%(s, getattr(event, s))
    print(k)
    if event.event_type == 'key down':
        if event.current_key  == 'Escape':
            hook.stop()
        elif event.current_key == 'LButton':
            cap_win_pic(event.mouse_x, event.mouse_y, 'click')

def main():
    win = app.top_window()
    w,h = util.Conf.WIN_WIDTH, util.Conf.WIN_HEIGHT
    #util.setWinPos(win.handle, 0,0, w, h)
    global of
    of = open(os.path.join(path, 'event_sequence.txt'), 'a')

##    listener = Listener(on_click=on_click, on_scroll=on_scroll)
##    listener.start()
##    with KBListener(on_press=on_press, on_release=on_release) as klistener:
##        klistener.join()
##    listener.stop()

    global hook
    hook = util.get_hooks(event_handler)
    hook.hook(True, True)

    of.close()

def make_CookieSet():
    import os
    COOKIE1='pt_pin=fdayok;pt_key=AAJhcenSADBAFuq4Sj6wVZhiZsHWB0YZQGfRwKwo2Edb1Vy5UqgufUpN8mcZIlIV006IA2oKPdI;'
    COOKIE2='pt_pin=mubaojie;pt_key=AAJhcekcADBrKLSv5gczCl1V46df4HrVoHbQNYYm8yZgL9EkorlhtqPdFaAzA2t-uX64Ba_ccC0;'
    COOKIE3='pt_pin=jd_WjohMbSkSEhV;pt_key=AAJhcelVADAx0LLgFMrxdVWWBU5Or3ZXSyPtOeIHCRAepMg-J1yvTZw3K5IWOizL4Xo5oR8vRnM;'
    COOKIE4='pt_pin=jd_78d5c6107d2e0;pt_key=AAJhcejcADA7mLq_XuEqR5Pd9ZZU_49sZZKoCwsxUH_Js3DvkuuAuHMvORM4BI0m4adOooVWH6s;'
    COOKIE5='pt_pin=jd_VwkKQtgodSKf;pt_key=AAJhcemGADCLCXpYnhdh1ZP2T56IPzs0-OhFVNxbCMMceUHfnRNE5gCiU_T68Y4GgIe4hJrkHaM;'

    o1 = {"cookie":COOKIE1, "userName":"fdayok"}
    o2 = {"cookie":COOKIE2, "userName":"mubaojie"}
    o3 = {"cookie":COOKIE3, "userName":"jd_WjohMbSkSEhV"}
    o4 = {"cookie":COOKIE4, "userName":"jd_78d5c6107d2e0"}
    o5 = {"cookie":COOKIE5, "userName":"jd_VwkKQtgodSKf"}
    import json
    data = {
    "JD_DailyBonusTimeOut": "0",
    "CookiesJD":json.dumps([o1]),
    "JD_DailyBonusDelay": "100"
    }
    for i, o in enumerate([o1,o2,o3,o4, o5]):
        data["CookiesJD"] = json.dumps([o])
        p = os.path.join('y:\\', 'CookieSet%d.json'%i)
        with open(p, 'w') as of:
            of.write(json.dumps(data))
        print('cp /mnt/sda4/CookieSet%d.json'%i, '/usr/share/jd-dailybonus/CookieSet.json')
        print('cd /usr/share/jd-dailybonus/')
        print('node ./JD_DailyBonus.js')

def compare_2_merged_list():
    import glob,os
    path = r'Y:\scripts'
    sys_path = '/mnt/sda4/scripts'
    list_file = os.path.join(path, 'docker', 'merged_list_file.sh')
    of = open(list_file, 'r')
    s = ''
    s = of.read()
    of.close()
    lst = glob.glob(os.path.join(path ,'jd*.ts'))
    mini = 0
    h = 1
    for p in lst:
        js = p.replace('.ts', '.js')
        if not os.path.exists(js):
            print(js, ' not exist')
            continue
        name = os.path.basename(js)
        if name in s:
            continue
        tmp = f'{mini} {h}/2 * * *  bash {sys_path}/ajd.sh  {sys_path}/{name}> {sys_path}/logs/{name}.log 2>&1'
        print(tmp)
        mini += 5
        if mini == 60:
            mini = 0
            h += 1
        if h == 24:
            h = 0


def test_qiye_weixin():
    import re

if __name__ == '__main__':
    main()
